<template>
  <view class="container">
    <view class="order-number-section">
      <text class="order-number-label">订单号：</text>
      <text class="order-number">{{ orderNumber }}</text>
    </view>
    <view v-for="(item, index) in formData" :key="index" class="evaluate-item">
      <!-- 商品信息 -->
      <view class="product-info">

        <image class="product-img" :src="orderItemDtos[index]?.pic" mode="aspectFill"></image>
        <text class="product-name">{{ orderItemDtos[index]?.prodName }}</text>
      </view>

      <!-- 评分 -->
      <view class="section">
        <text class="section-title">商品评分</text>
        <view class="star-rating">
          <text
            v-for="i in 5"
            :key="i"
            class="star"
            :class="i <= item.score ? 'active' : ''"
            @click="handleScoreChange(index, i)"
          >★</text>
        </view>
      </view>

      <!-- 评价类型 -->
      <view class="section">
        <text class="section-title">评价类型</text>
        <view class="evaluate-type">
          <button
            v-for="(type, typeIndex) in evaluateTypes"
            :key="typeIndex"
            :class="['type-btn', item.evaluate === typeIndex ? 'active' : '']"
            @click="item.evaluate = typeIndex"
          >{{ type }}</button>
        </view>
      </view>

      <!-- 评论内容 -->
      <view class="section">
        <textarea
          class="comment-input"
          v-model="item.content"
          :placeholder="`请输入${orderItemDtos[index]?.prodName}的评价（100字以内）`"
          maxlength="100"
        />
      </view>

      <!-- 图片上传 -->
      <view class="section">
        <view class="upload-header">
          <text class="section-title">上传图片</text>
          <text class="tips">（最多9张）</text>
        </view>
        <view class="upload-images">
          <view
            v-for="(img, imgIndex) in item.pics"
            :key="imgIndex"
            class="image-wrapper"
          >
            <image :src="img" class="preview-image" mode="aspectFill"></image>
            <text class="delete-icon" @click="deleteImage(index, imgIndex)">×</text>
          </view>
          <view
            v-if="item.pics.length < 9"
            class="upload-btn"
            @click="chooseImage(index)"
          >
            +
          </view>
        </view>
      </view>
    </view>

    <!-- 匿名评价 -->
    <view class="anonymous-section">
      <text>匿名评价</text>
      <switch
        :checked="isAnonymous"
        @change="isAnonymous = $event.detail.value"
      />
    </view>

    <button class="submit-btn" @click="handleSubmit">提交全部评价</button>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'



const orderItemDtos = ref<any[]>([])
const formData = ref<ProdCommParam[]>([])
const isAnonymous = ref(false)
const evaluateTypes = ['好评', '中评', '差评']
let orderNumber = ''
// 加载订单数据
const loadOrderDetail = (orderNumber: string) => {
  uni.showLoading()
  console.log('orderNumber', orderNumber)
  http.request({
    url: '/p/myOrder/orderDetail',
    method: 'GET',
    data: { orderNumber: orderNumber }
  }).then(({ data }) => {
    orderItemDtos.value = data.orderItemDtos

    initFormData()
    uni.hideLoading()
  })
}
// 处理评分变化
const handleScoreChange = (index: number, score: number) => {
  formData.value[index].score = score
}
// 初始化表单数据
const initFormData = () => {
  formData.value = orderItemDtos.value.map(item => ({
    prodId: item.prodId,
    orderItemId: item.orderItemId,
    score: 0,
    content: '',
    pics: [],
    isAnonymous: 0,
    evaluate: 0
  }))
}

// 图片选择
const chooseImage = async (index: number) => {
  try {
    const res = await uni.chooseImage({
      count: 9 - formData.value[index].pics.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    // 这里需要实现图片上传逻辑
    const uploadedUrls = await Promise.all(res.tempFilePaths.map(uploadImage))
    formData.value[index].pics.push(...uploadedUrls)
  } catch (err) {
    console.error(err)
  }
}

// 图片上传方法（需根据实际接口实现）
const uploadImage = async (tempFilePath: string) => {
  const res = await uni.uploadFile({
    url: 'http://localhost:8080/user/upload/evaluate',
    filePath: tempFilePath,
    name: 'file'
  })
  // 解析返回的JSON数据
  const response = JSON.parse(res.data)
  // 根据接口返回结构获取图片URL
  return response.data
}

// 删除图片
const deleteImage = (itemIndex: number, imgIndex: number) => {
  formData.value[itemIndex].pics.splice(imgIndex, 1)
}

// 提交全部评价
const handleSubmit = async () => {
  // 表单验证
  for (let i = 0; i < formData.value.length; i++) {
    const item = formData.value[i]
    if (!item.score) {
      uni.showToast({ title: `请为${orderItemDtos.value[i].prodName}评分`, icon: 'none' })
      return
    }
    if (!item.content.trim()) {
      uni.showToast({ title: `请输入${orderItemDtos.value[i].prodName}的评价内容`, icon: 'none' })
      return
    }
  }

  // 构造提交数据
  const submitData = formData.value.map(item => ({
    ...item,
    pics: item.pics.join(','),
    isAnonymous: isAnonymous.value,
    ordernum: orderNumber,
  }))

  try {
    // 这里调用批量评价接口
    await http.request({
      url: '/prodComm',
      method: 'POST',
      data: submitData
    })

    uni.showToast({ title: '评价成功' })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (err) {
    console.error(err)
    uni.showToast({ title: '提交失败', icon: 'none' })
  }
}

// 页面加载
onLoad((options: any) => {
  orderNumber = options.ordernum // 使用全小写获取参数
  loadOrderDetail(orderNumber)
})
</script>


<style scoped lang="scss">
.container {
  padding: 20rpx;
}

.order-number-section {
  padding: 30rpx;
  background: #f5f5f5;
  border-radius: 16rpx;
  margin: 20rpx;
  display: flex;
  align-items: center;

  .order-number-label {
    font-size: 28rpx;
    color: #666;
  }

  .order-number {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
    margin-left: 15rpx;
  }
}

.section {
  margin-top: 20rpx;
  padding: 30rpx;
  background: white;
  .section-title {
    font-size: 30rpx;
    color: #333;
    font-weight: bold;
  }
}

.star-rating {
  margin-top: 20rpx;
  .star {
    font-size: 50rpx;
    color: #ccc;
    margin-right: 20rpx;
    &.active {
      color: #ffd700;
    }
  }
}

.evaluate-type {
  display: flex;
  margin-top: 20rpx;
  .type-btn {
    margin-right: 20rpx;
    padding: 10rpx 30rpx;
    border-radius: 40rpx;
    font-size: 26rpx;
    background: #f5f5f5;
    &.active {
      background: #ffefcc;
      color: #f90;
    }
  }
}

.comment-input {
  width: 100%;
  height: 200rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.upload-header {
  display: flex;
  align-items: center;
  .tips {
    margin-left: 15rpx;
    font-size: 24rpx;
    color: #999;
  }
}

.upload-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
  .image-wrapper {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin: 0 20rpx 20rpx 0;
    .preview-image {
      width: 100%;
      height: 100%;
      border-radius: 8rpx;
    }
    .delete-icon {
      position: absolute;
      right: -10rpx;
      top: -10rpx;
      width: 40rpx;
      height: 40rpx;
      background: red;
      color: white;
      border-radius: 50%;
      text-align: center;
      line-height: 40rpx;
      font-size: 36rpx;
    }
  }
  .upload-btn {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #eee;
    border-radius: 8rpx;
    font-size: 60rpx;
    color: #ccc;
    text-align: center;
    line-height: 200rpx;
  }
}

.anonymous-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  margin-top: 20rpx;
  background: white;
  font-size: 30rpx;
}

.submit-btn {
  margin: 40rpx 30rpx;
  background: #ff9000;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
}
.evaluate-item {
  margin-bottom: 30rpx;
  background: white;
  padding: 20rpx;
  border-radius: 16rpx;
}

.product-section {
  border-bottom: 1rpx solid #eee;
  padding-bottom: 30rpx;
  margin-bottom: 30rpx;

  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
}
</style>
